<template>
    <Popup ref="popupRef" :loading="loading" :title="modeTitle" :formData="formData" :width="500" :height="500" @submit="handleSubmit"
    @cancel="handleCancel">
        <template #default="{ formData }">
            <a-form-item label="角色名称" field="name">
                <m-form-input v-model="formData.name" placeholder="请输入角色名称" />
            </a-form-item>
            <a-form-item label="角色描述" field="description">
                <m-form-input v-model="formData.description" placeholder="请输入角色描述" />
            </a-form-item>
            <a-form-item label="状态" field="status">
                <a-switch v-model="formData.status" />
            </a-form-item>
            {{ formData }}
        </template>
    </Popup>
</template>

<script setup lang="ts">
import Popup from '@/components/Popup/index.vue'
import { addRole, updateRole } from '@/api/system/auth/role'
const popupRef = ref<InstanceType<typeof Popup>>()

const mode = ref<'add' | 'edit'>('add')

const modeTitle = computed(() => {
    return mode.value === 'add' ? '新增角色' : '编辑角色'
})

const emits = defineEmits<{
    (e: 'success', data?: any): void
}>()

interface FormData {
    id: string
    name: string
    description: string
    status: boolean
}
const loading = ref(false)

const formData = reactive<FormData>({
    id: '',
    name: '',
    description: '',
    status: false,
})

const handleSubmit = async (data: FormData) => {
    try {
        mode.value === 'add' ? await addRole(data) : await updateRole(data)
        popupRef.value?.close()
        popupRef.value?.closeLoading()
        emits('success', data)
    } catch (error) {
        popupRef.value?.closeLoading()
    }
}

const handleCancel = () => {
    loading.value = false
    popupRef.value?.close()
}

const open = (type: any) => {
    mode.value = type
    popupRef.value?.open()
}

const setFormData = async (record: Record<any, any>) => {
    if (record) {
        // 使用解构赋值来合并数据

        for (const key in formData) {
            if (record[key] != null && record[key] != undefined) {
                //@ts-ignore
                formData[key] = record[key]
            }
        }

        // Object.assign(formData, rest)
        // 确保弹窗组件也更新了数据
        nextTick(() => {
            popupRef.value?.setFormData(formData)
        })
    }

}


defineExpose({
    open,
    setFormData
})

</script>

<style scoped lang="scss"></style>
